import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class MyClient {
    public static void main(String[] args) throws IOException {
    	
    	MyClient client = new MyClient();
    	
        if (args.length != 1) {
             System.out.println("Usage: java QuoteClient <hostname>");
             return;
        }

        int[] values = client.readInputValues();
        
        DatagramSocket socket = null;
        DatagramPacket packet = null;
        byte[] buf = null;
        System.out.println("----------------> Client Send Packets:");
        for (int i=0; i < MyServer.EXP_NUM_PACKETS; ++i) {
        	socket = new DatagramSocket();
        	     
       		// send request
	        buf = client.createData(values[i], i);
        
	        InetAddress address = InetAddress.getByName(args[0]);
	        packet = new DatagramPacket(buf, buf.length, address, 4445);
	        socket.send(packet);
	        
        	System.out.println((i+1) + ", " + values[i]);
        }
    
            // get response once all sent
        buf = new byte[15];
        packet = new DatagramPacket(buf, 15);
        socket.receive(packet);

        String received = new String(packet.getData());
        System.out.println("Server Response: " + received);
    
        socket.close();
    }

    
    private int[] readInputValues() {
    	int[] values = null;
    	
		try {
	        String sCurrentLine;
	 
	        FileReader r = new FileReader(
					MyClient.class.getClassLoader().getResource(MyServer.FILE_NAME).getPath()
			        .replaceAll("%20", " "));
	        BufferedReader br = 
	            new BufferedReader(r);
	        
	        values = new int[MyServer.EXP_NUM_PACKETS];
	        int i = 0;
	        while ((sCurrentLine = br.readLine()) != null) {
	        	values[i++] = Integer.valueOf(sCurrentLine);
	        	//System.out.println(i + ", " + sCurrentLine);
	        }

		    
		} catch (FileNotFoundException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    
	    return values;
    }
    
    private byte[] createData(int value, int seq) {
		byte byToIn[] = new byte[8];
		
		byToIn[0] = (byte) value;
		byToIn[1] = (byte)(value >>> 8);
		byToIn[2] = (byte)(value >>> 16);
		byToIn[3] = (byte)(value >>> 24);
		byToIn[4] = (byte)(seq >>> 32);
		byToIn[5] = (byte)(seq >>> 40);
		byToIn[6] = (byte)(seq >>> 48);
		byToIn[7] = (byte)(seq >>> 56);
		
		return byToIn;
    }
}
